<template>
	<view class="login page">
		<button class="r-btn" v-if="register" open-type="getUserInfo" @getuserinfo='getUserInfo'>微信注册</button>
		<!-- <button class="r-btn" v-if="userInfo" open-type="getPhoneNumber" @getphonenumber='getPhone'>点击完成注册</button> -->
		<!-- <input type="text" placeholder="推荐人编号" v-if="options.shareTicket"> -->
	</view>
</template>

<script>
	import {
		login,
		testLogin,
		register,
		getShareInfo
	} from '@/api/user.js'
	import {
		getPath,
		setToken,
		setUserInfo
	} from '@/storage/index.js'
	import {
		mapActions,
		mapState
	} from 'vuex'



	export default {
		onLoad() {
			this.login()
		},
		computed: {
			...mapState({
				options: state => state.wx.options
			})
		},
		methods: {
			getUserInfo(e) {
				let pid = 0;
				if(this.options.query.pid){
					pid = this.options.query.pid
				}
				console.log(pid+"==>")
				//注册
				register(pid, e.detail.userInfo.avatarUrl,e.detail.userInfo.nickName, this.openId, this.unionId).then(res => {
					this.afterLogin(res)
				})

			},
			testLogin() {
				let code = "AA205279"
				testLogin(code).then(res => {
					if (res.data) {
						this.afterLogin(res)
					} else {
						this.notLogin(res)
					}
				})
			},
			login() {
				uni.login({
					provider: 'weixin',
					success: (loginRes) => {
						login(loginRes.code).then(res => {
							if (res.data) { // 登录成功
								this.afterLogin(res)
							} else {

								this.notLogin(res)
							}
						})
					}
				})
			},
			afterLogin(res) {
				setUserInfo(res.extra.user)
				setToken(res.data)
				let path = getPath()
				if(TABS.indexOf(path)>-1){
					this.$Router.pushTab(path)
				}else{
					this.$Router.replace(path)
				}
				
			
			},
			notLogin(res) {
				this.openId = res.extra.wxUser.openId
				this.unionId = res.extra.wxUser.unionId
				this.register = true
			},
			...mapActions([
				'updateCartCount',
				'setToken',
				'updateUser'
			])
		},
		data() {
			return {
				userInfo: null,
				topUserId: null,
				register: false,
				openId: null,
				unionId: null
			};
		}
	}
</script>

<style lang="stylus">
	.login 
		display flex 
		align-items center 
		.r-btn 
			background-color #009C4E 
			color white
</style>
